package com.example.controller;

import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        return "hello world";
    }


    @GetMapping("/haha")
    public Mono<String> haha() {
        return Mono.just("ddd");
    }

    @GetMapping("/hehe")
    public Flux<String> hehe() {
        return Flux.just("ddd", "@");
    }


    @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> sse() {
        return Flux.range(1, 10)
                .map(integer -> {
                    return ServerSentEvent.builder("ha-" + integer)
                            .id(integer + "")
                            .comment("hei-" + integer)
                            .event("haha")
                            .build();
                }).delayElements(Duration.ofMillis(500));
    }
}
